package edu.zju.gis.dbfg.server.util;

import org.json.JSONArray;
import org.json.JSONObject;

public final class LogUtil {

    public static String getSparkTaskLogByName(String sparkTaskId, String monitorPath) {
        try {
            String appList = HttpRequestUtil.get(monitorPath, null, "utf-8");
            String appId = "";
            JSONArray apps = new JSONObject(appList).getJSONObject("apps").getJSONArray("app");
            for (int i = 0; i < apps.length(); i++) {
                JSONObject app = apps.getJSONObject(i);
                if (app.getString("name").equals(sparkTaskId)) {
                    appId = app.getString("id");
                    break;
                }
            }
            String monitorResult = HttpRequestUtil.get(monitorPath + "/" + appId, null, "utf-8");
            JSONObject app = new JSONObject(monitorResult).getJSONObject("app");
            String logPage = HttpRequestUtil.get(app.getString("amContainerLogs") + "/stdout", null, "utf-8");
//            int index = logPage.indexOf("<td class=\"content\">");
//            String tail = logPage.substring(index, logPage.length() - 1);
            int h1IndexF = logPage.indexOf("<pre>") + 5;
            int h1IndexL = logPage.indexOf("</pre>");
            return logPage.substring(h1IndexF, h1IndexL).trim();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "请稍后再试。";
        }
    }
}
